﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace ADRoot
{
    // 3des加密解密
    class Encryption
    {

        ///   <summary> 
        ///   加密 
        ///   </summary> 
        ///   <param   name= "strString "> </param> 
        ///   <param   name= "strKey "> </param> 
        ///   <param   name= "encoding "> </param> 
        ///   <returns> </returns> 
        public static string Encrypt3DES(string strString, string strKey, Encoding encoding)
        {
            TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();
            MD5CryptoServiceProvider hashMD5 = new MD5CryptoServiceProvider();

            DES.Key = hashMD5.ComputeHash(encoding.GetBytes(strKey));
            DES.Mode = CipherMode.ECB;

            ICryptoTransform DESEncrypt = DES.CreateEncryptor();

            byte[] Buffer = encoding.GetBytes(strString);
            return Convert.ToBase64String(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
        }

        ///   <summary> 
        ///   解密 
        ///   </summary> 
        ///   <param   name= "strString "> </param> 
        ///   <param   name= "strKey "> </param> 
        ///   <returns> </returns> 
        public static string Decrypt3DES(string strString, string strKey)
        {
            TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();
            MD5CryptoServiceProvider hashMD5 = new MD5CryptoServiceProvider();

            DES.Key = hashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strKey));
            DES.Mode = CipherMode.ECB;
            ICryptoTransform DESDecrypt = DES.CreateDecryptor();
            string result = " ";
            try
            {
                byte[] Buffer = Convert.FromBase64String(strString);
                result = ASCIIEncoding.ASCII.GetString(DESDecrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
            }
            catch (System.Exception e)
            {
                throw (new System.Exception("null ", e));
            }
            return result;
        }
    }
}
